import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/material.dart';
import 'package:fsharing/core/constants/app_contstants.dart';
import 'package:fsharing/core/models/business_type.dart';
import 'package:fsharing/core/viewmodels/app_model.dart';
import 'package:fsharing/core/viewmodels/pages/mine/manage/business_type_model.dart';
import 'package:fsharing/core/viewmodels/view_model.dart';
import 'package:fsharing/main.dart';
import 'package:fsharing/ui/pages/mine/webview_page.dart';
import 'package:fsharing/ui/widgets/background_container.dart';
import 'package:fsharing/ui/widgets/round_back_button.dart';
import 'package:provider/provider.dart';

class BusinessTypePage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return ChangeNotifierProvider(
      create: (context) => BusinessTypeModel(Provider.of(context, listen: false)),
      child: BackgroundContainer(
        child: Scaffold(
          appBar: AppBar(
            leading: RoundBackButton(),
            title: Text('业务类型'),
          ),
          body: _ViewStateWidget(),
        ),
      ),
    );
  }
}

class _ViewStateWidget extends StatelessWidget {
  const _ViewStateWidget({
    Key key,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    BusinessTypeModel businessApplyModel = Provider.of(context);
    switch (businessApplyModel.viewState) {
      case ViewState.busy:
        return Center(
          child: CircularProgressIndicator(),
        );
      case ViewState.error:
        return Center(
          child: Text(businessApplyModel.errorMessage),
        );
      case ViewState.success:
        return _SuccessWidget(
          list: businessApplyModel.list,
        );
      default:
        return Container();
    }
  }
}

class _SuccessWidget extends StatelessWidget {
  final List<BusinessType> list;

  const _SuccessWidget({
    Key key,
    @required this.list,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return CustomScrollView(
      slivers: <Widget>[
        SliverToBoxAdapter(
          child: _HeaderWidget(),
        ),
        SliverFixedExtentList(
          delegate: SliverChildBuilderDelegate(
            (context, index) {
              return _ListItemWidget(
                businessType: list[index],
              );
            },
            childCount: list.length,
          ),
          itemExtent: 68,
        ),
      ],
    );
  }
}

class _HeaderWidget extends StatelessWidget {
  const _HeaderWidget({
    Key key,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Container(
      alignment: Alignment.centerLeft,
      padding: EdgeInsets.symmetric(horizontal: 20),
      decoration: BoxDecoration(
        image: DecorationImage(
          image: AssetImage('assets/images/business/img_header.png'),
          fit: BoxFit.fill,
        ),
      ),
      height: 45,
      child: Text(
        '选择需申请的业务',
        style: TextStyle(fontSize: 17),
      ),
    );
  }
}

class _ListItemWidget extends StatelessWidget {
  final BusinessType businessType;

  const _ListItemWidget({
    Key key,
    @required this.businessType,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Theme(
      data: lightTheme(),
      child: Material(
        child: InkWell(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: <Widget>[
              Container(),
              Row(
                children: <Widget>[
                  SizedBox(width: 20),
                  ClipRRect(
                    borderRadius: BorderRadius.circular(4),
                    child: CachedNetworkImage(
                      imageUrl: businessType.typeImageUrl,
                      width: 48,
                      height: 48,
                      fit: BoxFit.fill,
                    ),
                  ),
                  SizedBox(width: 12),
                  Expanded(
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: <Widget>[
                        Text(
                          businessType.businessName,
                          style: TextStyle(fontSize: 17),
                        ),
                        SizedBox(height: 4),
                        Text(
                          '(${businessType.description})',
                          style: TextStyle(color: Colors.grey, fontSize: 10),
                        ),
                      ],
                    ),
                  ),
                  Column(
                    crossAxisAlignment: CrossAxisAlignment.end,
                    children: <Widget>[
                      Text.rich(
                        TextSpan(
                          text: '当前级别：',
                          style: TextStyle(color: Colors.grey),
                          children: [TextSpan(text: businessType.curBusinessLevelName)],
                        ),
                      ),
                      if (businessType.endTime != null)
                        Text(
                          '${businessType.endTime}',
                          style: TextStyle(color: Colors.grey),
                        ),
                    ],
                  ),
                  SizedBox(width: 12),
                ],
              ),
              Divider(
                height: 1,
                indent: 12,
                endIndent: 12,
                color: Color(0xFFE6E6E6),
              ),
            ],
          ),
          onTap: () => _onItemClicked(context),
        ),
      ),
    );
  }

  void _onItemClicked(BuildContext context) async {
    // 申请前需要先同步协议
    AppStoreModel appStoreModel = Provider.of(context, listen: false);
    final result = await Navigator.of(context).pushNamed(
      '/webview',
      arguments: WebViewPageArgs(
        '第三方业务协议',
        '请仔细阅读以下条款：',
        '$api_base_url/app/protocol/business?sid=${appStoreModel.bindingStoreId}',
        query: true,
      ),
    );
    if (!(result is bool && result)) {
      // 没有点同意协议，不能申请
      return;
    }
    // 导航业务级别
    Navigator.of(context).pushNamed('/business/level', arguments: businessType);
  }
}
